<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useDrag ,useDrop } from 'vue3-dnd'

import type { ILayer } from '@/utils/layer'
import { PaintBoard } from '@/utils/paintBoard'

  // 初始化dnd ref
import HiddenIcon from '@/components/icons/hiddenC.vue'
import ShowIcon from '@/components/icons/showC.vue'

interface IProps {
  board: PaintBoard | undefined // 画板
  data: ILayer // 图层数据
  index: number // 图层下标
  refresh: () => void // 刷新事件
}
const { index,board,data,refresh} = defineProps<IProps>()

const dndRef = ref<Element>()
const [, drop] = useDrop<{ index: number }>({
  accept: 'layer',
  drop(hoverItem) {
    if (hoverItem.index === index) {
      return
    }
    if (board && dndRef.value) {
      board.layer.swap(index, hoverItem.index)
      board.sortOnLayer()
      board.render()
      refresh()
    }
  }
})
const [isDragging, drag] = useDrag({
  type: 'layer',
  item: { index },
  collect: (monitor)=>{
    return monitor.isDragging()
  }
})


onMounted(()=>{
  drop(drag(dndRef as any))
})
/**
 * 更新当前图层
 * @param id 图层id
 */
  const updateCurrentLayer = (id: number) => {
  if (board) {
    board.layer.updateCurrent(id)
    refresh()
  }
}

/**
 * 修改图层标题
 * @param id 图层id
 * @param title 图层标题
 */
const setLayerTitle = (id: number, title: string) => {
  if (board) {
    board.layer.updateTitle(id, title)
    refresh()
  }
}

/**
 * 修改图层展示状态
 * @param id 图层id
 * @param show 展示状态
 */
const setLayerShow = (id: number, show: boolean) => {
  if (board) {
    board.select.cancelSelectElement()
    board.layer.updateShow(id, show)
    refresh()
  }
}
</script>

<template>
  <div ref="dndRef"> 
    <div class="flex justify-evenly py-1.5 cursor-pointer" 
      :class="{'bg-primary':board?.layer.current === data.id,'opacity-50':isDragging}"
      @click="updateCurrentLayer(data.id)"
      >
      <input 
        type="text"
        class="px-2 w-40"
        v-model="data.title"
        @input="(e)=>{setLayerTitle(data.id, (e.target as HTMLInputElement).value)}"
      />
      <div
        class="cursor-pointer"
        @click="(e)=>{
          e.stopPropagation()
          setLayerShow(data.id, !data.show)
        }">
        <ShowIcon v-if="data.show"></ShowIcon>
        <HiddenIcon v-else ></HiddenIcon>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>
